package zm.irc.threads;

import org.apache.log4j.Logger;
import zm.irc.client.IrcChannel;
import zm.irc.client.IrcClient;
import zm.irc.ioc.annotation.AutoWired;
import zm.irc.ioc.annotation.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;

import com.mysql.cj.util.StringUtils;

@Service
public class CommandLineInputThread extends IrcThread{
    private static Logger log = Logger.getLogger(CommandLineInputThread.class);

    @AutoWired
    private IrcClient ircClient;

    private  BufferedReader br;


    @Override
    public void beforeLoop(){
        log.info("消息输入线程启动！");
        this.br = new BufferedReader(new InputStreamReader(System.in));
        log.info("消息输入线程成功！");
    }


    private String msgStr;

    @Override
    public void before()throws Exception{
        try{
            msgStr = this.br.readLine();
        }catch(Exception e){
            this.stopIrcThread();
            log.error("CommandLine read error.Stop this thread!",e);
        }
    }

    @Override
    public void doRun() {
        try {
            if (StringUtils.isEmptyOrWhitespaceOnly(msgStr)) {
                Thread.sleep(80);
                return;
            }
            if (msgStr.startsWith("/zc")) {
                this.processAsCommand(msgStr);
                return;
            }
            IrcChannel channel = ircClient.getCurrentChannel();
            if (channel != null) {
                channel.send(msgStr);
            } else {
                log.error("Channel is empty!");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    private void processAsCommand(String command){
        String param[] = command.split(" ");
        if("SC".equals(param[1])){
            String channelName = param[2];
            this.ircClient.switchChannel(channelName);
        }else if("join".equals(param[1])){
            String channelName = param[2];
            this.ircClient.join(channelName);
        }
    }
}
